/*
XPTracker - Alternative Agile Tracking Tool
Copyright (C) 2006-2009  Stephen Starkey

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
package org.xptracker.web;

import com.google.inject.Inject;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.security.action.Secure;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xptracker.domain.*;
import org.xptracker.persistence.PersistenceManager;
import org.xptracker.port.BugzillaImporter;
import org.xptracker.port.CsvExporter;
import org.xptracker.port.CsvImporter;
import org.xptracker.port.XPlannerImporter;
import org.xptracker.services.JobScheduler;
import org.xptracker.wiki.ExternalLinkWidget;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@UrlBinding("/Admin.action")
@Secure(roles = "admin")
public class AdminActionBean extends StandardActionBean {
  private static final String EXAMPLE_FORMAT = "http://localhost/system?id={0}";
  private static final Log logger = LogFactory.getLog(AdminActionBean.class);

  @SuppressWarnings({"UnusedDeclaration"})
  @Inject
  private CsvExporter csvExporter;

  @SuppressWarnings({"UnusedDeclaration"})
  @Inject
  private CsvImporter csvImporter;

  @SuppressWarnings({"UnusedDeclaration"})
  @Inject
  private BugzillaImporter bugzillaImporter;

  public static enum Type {
    users, stories, customers, xplanner, bugzilla
  }

  private Map<String, Integer> points;
  private Type importType;
  private List<ScheduledTask> scheduledTasks;
  private FileBean fileBean;
  private ScheduledTask task;
  public Map<String, String> linkFormats;
  private String formatName;

  public List<ScheduledTask> getScheduledTasks() {
    return scheduledTasks;
  }

  public void setScheduledTasks(List<ScheduledTask> scheduledTasks) {
    this.scheduledTasks = scheduledTasks;
  }

  public ScheduledTask getTask() {
    return task;
  }

  public void setTask(ScheduledTask task) {
    this.task = task;
  }

  public Map<String, Integer> getPoints() {
    return points;
  }

  public void setPoints(Map<String, Integer> points) {
    this.points = points;
  }

  public Type getImportType() {
    return importType;
  }

  public void setImportType(Type importType) {
    this.importType = importType;
  }

  public Map<String, String> getLinkFormats() {
    return linkFormats;
  }

  public void setLinkFormats(Map<String, String> linkFormats) {
    this.linkFormats = linkFormats;
  }

  public String getFormatName() {
    return formatName;
  }

  public void setFormatName(String formatName) {
    this.formatName = formatName;
  }

  @DefaultHandler
  public Resolution loadAdmin() {
    return new ForwardResolution("/admin/admin.jsp");
  }

  @HandlesEvent("AddLinkFormat")
  public Resolution addFormat() {
    linkFormats.put(formatName, EXAMPLE_FORMAT);
    saveLinkFormats();
    addMessage("Format added: " + formatName);
    return new RedirectResolution(getClass());
  }

  @HandlesEvent("DeleteLinkFormat")
  public Resolution deleteFormat() {
    linkFormats.remove(formatName);
    saveLinkFormats();
    addMessage("Format removed: " + formatName);
    return new RedirectResolution(getClass());
  }

  private void saveLinkFormats() {
    persistenceManager.inTransaction(new PersistenceManager.UpdateHandler() {
      public Object doUpdate(PersistenceManager.UpdateReceiver receiver) {
        NamedMap oldFormats = domain.getNamedMap(receiver, ExternalLinkWidget.CUSTOM_LINKS);
        receiver.remove(oldFormats);
        receiver.insert(new NamedMap(ExternalLinkWidget.CUSTOM_LINKS, linkFormats));
        return null;
      }
    });
  }

  @HandlesEvent("SaveLinkFormats")
  public Resolution saveFormats() {
    saveLinkFormats();
    addMessage("Formats saved");
    return new RedirectResolution(getClass());
  }

  @HandlesEvent("SetStoryPoints")
  public Resolution saveStoryPoints() {
    return persistenceManager.inTransaction(new PersistenceManager.UpdateHandler<Resolution>() {
      public Resolution doUpdate(PersistenceManager.UpdateReceiver receiver) {
        StoryPointMapping mapping = domain.loadPointMapping(false);
        receiver.remove(mapping);
        receiver.insert(new StoryPointMapping(points));
        addMessage("Point mapping saved.");
        return returnToAdminPage();
      }
    });
  }

  @HandlesEvent("LoadTask")
  public Resolution loadTask() {
    this.task = domain.loadEntity(ScheduledTask.class, param("taskId"));
    getContext().getRequest().setAttribute("type", "Edit");
    return new ForwardResolution("/admin/editTask.jsp");
  }

  @HandlesEvent("NewTask")
  public Resolution newTask() {
    this.task = new ScheduledTask();
    getContext().getRequest().setAttribute("type", "Add");
    return new ForwardResolution("/admin/editTask.jsp");
  }

  @HandlesEvent("EditTask")
  public Resolution editTask() {
    return persistenceManager.inTransaction(new PersistenceManager.UpdateHandler<Resolution>() {
      public Resolution doUpdate(PersistenceManager.UpdateReceiver receiver) {
        ScheduledTask newTask = domain.loadEntity(ScheduledTask.class, task.getId());
        if (!newTask.isSystem()) {
          newTask.setName(task.getName());
          newTask.setScript(task.getScript());
        }
        newTask.setCronSchedule(task.getCronSchedule());
        receiver.update(newTask);
        taskChanged(task, "updated");
        return returnToAdminPage();
      }
    });
  }

  @HandlesEvent("AddTask")
  public Resolution addTask() {
    return persistenceManager.inTransaction(new PersistenceManager.UpdateHandler<Resolution>() {
      public Resolution doUpdate(PersistenceManager.UpdateReceiver receiver) {
        receiver.insert(task);
        taskChanged(task, "created");
        return returnToAdminPage();
      }
    });
  }

  private void restartScheduler() {
    JobScheduler.start();
    getContext().getMessages().add(new SimpleMessage("Job Scheduler Restarted."));
  }

  @HandlesEvent("DisableTask")
  public Resolution disableTask() {
    return taskDisabled(true);
  }

  @HandlesEvent("EnableTask")
  public Resolution enableTask() {
    return taskDisabled(false);
  }

  @HandlesEvent("DeleteTask")
  public Resolution deleteTask() {
    return persistenceManager.inTransaction(new PersistenceManager.UpdateHandler<Resolution>() {
      public Resolution doUpdate(PersistenceManager.UpdateReceiver receiver) {
        ScheduledTask task = loadEntity(ScheduledTask.class, param("taskId"));
        if (!task.isSystem()) {
          receiver.remove(task);
          taskChanged(task, "deleted");
        }
        return returnToAdminPage();
      }
    });
  }

  private Resolution taskDisabled(final boolean disabled) {
    return persistenceManager.inTransaction(new PersistenceManager.UpdateHandler<Resolution>() {
      public Resolution doUpdate(PersistenceManager.UpdateReceiver receiver) {
        ScheduledTask task = loadEntity(ScheduledTask.class, param("taskId"));
        task.setDisabled(disabled);
        receiver.update(task);
        taskChanged(task, disabled ? "Disabled" : "Enabled");
        return returnToAdminPage();
      }
    });
  }

  private void taskChanged(ScheduledTask task, String thingWeDid) {
    getContext().getMessages().add(new SimpleMessage("Task ''{0}'' {1}.", task.getName(), thingWeDid));
    restartScheduler();
  }

  @HandlesEvent("Export")
  public Resolution export() {
    final ByteArrayOutputStream stream = new ByteArrayOutputStream();
    final Domain domain = this.domain;
    switch(importType) {
      case users:
        csvExporter.exportUsers(stream, domain.listUsers(true));
        break;
      case stories:
        csvExporter.exportStories(stream, domain.listStories());
        break;
      case customers:
        csvExporter.exportCustomers(stream, domain.listCustomers());
        break;
    }

    return new StreamingResolution("text/xml") {
      public void stream(HttpServletResponse response) throws Exception {
        stream.writeTo(response.getOutputStream());
      }
    }.setFilename("xptracker_export.csv");
  }

  @HandlesEvent("Import")
  public Resolution doImport() {
    return persistenceManager.inTransaction(new PersistenceManager.UpdateHandler<Resolution>() {
      public Resolution doUpdate(PersistenceManager.UpdateReceiver receiver) {
        final User user = getCurrentUser();
        try {
          final InputStream inputStream = fileBean.getInputStream();
          switch (importType) {
            case users:
              Collection<User> importedUsers = csvImporter.importUsers(inputStream);
              createUsers(importedUsers, receiver);
              break;
            case stories:
              Collection<Story> importedStories = csvImporter.importStories(inputStream, receiver);
              createStories(importedStories, user, receiver);
              break;
            case customers:
              createCustomers(csvImporter.importCustomers(inputStream), receiver);
              break;
            case xplanner:
              //todo Make this injectable!
              XPlannerImporter.importData(inputStream, receiver, domain, getCurrentUser());
              addMessage("Finished importing from XPlanner");
              break;
            case bugzilla:
              bugzillaImporter.importData(inputStream, receiver, getCurrentUser());
              addMessage("Bugzilla import complete.");
              break;
          }
        } catch (IOException e) {
          logger.error("An error occurred trying to import...", e);
          throw new RuntimeException("An error occurred trying to import " + e);
        }
        return returnToAdminPage();
      }
    });
  }

  protected RedirectResolution returnToAdminPage() {
    return new RedirectResolution(AdminActionBean.class);
  }

  private void createCustomers(Collection<Customer> customers, PersistenceManager.UpdateReceiver receiver) {
    int customerCount = 0;
    for(Customer c : customers) {
      if(domain.loadCustomer(c.getName()) == null ) {
        receiver.insert(c);
        addMessage("Customer created: " + c);
        customerCount ++;
      }
    }
    if(customerCount > 0) {
      addMessage("Customers created: " + customerCount);
    }
  }
  private void createStories(Collection<Story> stories, User user, PersistenceManager.UpdateReceiver receiver) {
    if (!stories.isEmpty()) {
      for (Story story : stories) {
        receiver.insert(story);
        addMessage("Story created: " + story);
      }
      addMessage("Stories Created: " + stories.size());
    }
  }

  private void createUsers(Collection<User> users, PersistenceManager.UpdateReceiver receiver) {
    int createdUsers = 0;
    for (User newUser : users) {
      if (domain.loadUser(newUser.getUsername()) != null) {
        continue;
      }
      final String password = StringUtils.reverse(newUser.getUsername());
      newUser.setPassword(password);
      receiver.insert(newUser);
      addMessage("User created: " + newUser.getUsername() + " their password is their username backwards (" + password + ")");
      createdUsers++;
    }
    addMessage("Users created: " + createdUsers);
  }

  public FileBean getFileBean() {
    return fileBean;
  }

  public void setFileBean(FileBean fileBean) {
    this.fileBean = fileBean;
  }

  @Before(stages=LifecycleStage.BindingAndValidation)
  public void loadRequiredData() {
    scheduledTasks = domain.listScheduledTasks();
    points = domain.loadPointMapping(true).getMap();
    Collections.sort(scheduledTasks, new BeanComparator("name"));
    persistenceManager.inTransaction(new PersistenceManager.UpdateHandler() {
      public Object doUpdate(PersistenceManager.UpdateReceiver receiver) {
        NamedMap namedMap = domain.getNamedMap(receiver, ExternalLinkWidget.CUSTOM_LINKS);
        linkFormats = namedMap.map;
        return null;
      }
    });
  }
}
